package cn.sanch.basic.controller;

import cn.sanch.basic.dto.SmsDto;
import cn.sanch.basic.service.IVerifyCodeService;
import cn.sanch.basic.util.AjaxResult;
import cn.sanch.basic.util.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 接口类：验证码
 * 1.图形验证码
 * 2.手机短信验证码
 * @author sanch37
 * 2022/6/5
 */
@RestController
@RequestMapping("/verifyCode")
public class verifyCodeController {


    @Autowired
    private IVerifyCodeService verifyCodeService;

    /**
     * 接口：获取图形验证码
     * @param key
     * @return
     */
    @GetMapping("/image/{key}")
    public AjaxResult getImageCode(@PathVariable("key") String key) {

        try {
            //调用业务层方法获取验证码通过base64编码后的字符串
            String base64Str = verifyCodeService.getImageCode(key);
            //直接设置进AjaxResult里的resultObj里返回给前端
            return AjaxResult.me().setResultObj(base64Str);
        } catch (BusinessException b) { //业务错误
            b.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取失败！" + b.getMessage());
        } catch (Exception e) { //500
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器繁忙！请稍后重试！");
        }
    }


    /**
     * 接口：发送手机验证码
     * @param smsDto
     * @return
     */
    @PostMapping("/smsCode")
    public AjaxResult sendPhoneCode(@RequestBody SmsDto smsDto) {
        try {

            verifyCodeService.sendPhoneCode(smsDto);
            return AjaxResult.me();
        } catch (BusinessException b) { //业务错误
            b.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取失败！" + b.getMessage());
        } catch (Exception e) { //500
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器繁忙！请稍后重试！");
        }
    }


    /**
     * 接口：微信扫码登录绑定手机发送手机验证码
     * @param smsDto
     * @return
     */
    @PostMapping("/binderSmsCode")
    public AjaxResult binderSmsCode(@RequestBody SmsDto smsDto) {
        try {

            verifyCodeService.binderSmsCode(smsDto);
            return AjaxResult.me();
        } catch (BusinessException b) { //业务错误
            b.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取失败！" + b.getMessage());
        } catch (Exception e) { //500
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器繁忙！请稍后重试！");
        }
    }

}
